
const getListToTree = (array = [], upKey) => {

    let list = []
    if (array.length === 0) return list;
    // 除去parentKey节点不相等的剩余节点
    const arr = array.filter((item, index) => {
        const {
            id = undefined,
            parentId = String,
            className = String,
            sort = Number,
            status = String
        } = item;

        if (parentId !== upKey) {
            return {
                id: id,
                parentId,className,sort,status
            }
        }
    })
    array.forEach((item, i) => {
        const {
            id,
            parentId = String,
            className = String,
            sort = Number,
            status = String
        } = item;
        if (parentId === upKey ) {
            list.push({
                id: id,
                parentId,className,sort,status,
                children: getListToTree(arr, id)
            })
        }
    })
    return list;
}

const getPermissionConfigTree = (array, upKey) => {
    let list = []
    // 除去parentId节点不相等且不是menu的剩余节点
    const arr = array.filter((item, index) => {
        const {id,
            parentId,className,sort,status } = item;
        if (parentId !== upKey ) {
            return {
                id,
                parentId,className,sort,status

            }
        }
    })

    // 剩下的节点 父节点相等，
    array.forEach((item, i) => {

        const { id,
            parentId,className,sort,status} = item;

        if (parentId === upKey ) {
            list.push({
                id,  parentId,className,sort,status,
                children: getPermissionConfigTree(arr, id).length > 0 ? getPermissionConfigTree(arr, id) : undefined,
            })
        }
    })

    return list;

}
// 过滤数据
const getCateTreeForPermission = (allTree, permissionList) => {
    const filter = (list) => {
        let res = [];
        list.forEach(item => {
            if (item.children.length > 0) {
                res.push({
                    ...item,
                    children: filter(item.children)
                })
            }
            permissionList.includes(item.key) && res.push(item);
        })
        return res;
    }
    let res = filter(allTree);
    return res;
}

module.exports = {
    getListToTree,
    getPermissionConfigTree,
    getCateTreeForPermission
}
